package com.wlz.framework.protocol.http;

import com.wlz.framework.Invocation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wlz
 * @date 2022-07-11  9:22 下午
 */
@Slf4j
public class HttpClient {

    public String send(String hostname, Integer port, Invocation invocation) {
        // 读取用户的配置

        try {
            URL url = new URL("http", hostname, port, "/");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);

            OutputStream outputStream = httpURLConnection.getOutputStream();
            ObjectOutputStream oss = new ObjectOutputStream(outputStream);

            oss.writeObject(invocation);
            oss.flush();
            oss.close();

            InputStream inputStream = httpURLConnection.getInputStream();

            String result = IOUtils.toString(inputStream);

            return result;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
